package com.easysettle

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.budiyev.android.codescanner.AutoFocusMode
import com.budiyev.android.codescanner.CodeScanner
import com.budiyev.android.codescanner.CodeScannerView
import com.budiyev.android.codescanner.DecodeCallback
import com.budiyev.android.codescanner.ErrorCallback
import com.budiyev.android.codescanner.ScanMode
import com.easysettle.databinding.ItemCartBinding
import com.easysettle.model.CartItem
import com.easysettle.model.Product
import com.easysettle.service.MainService
import java.text.SimpleDateFormat
import java.util.*

/**
 * 扫描与购物车合并Activity
 * 用于同时提供商品扫描识别和购物车管理功能
 */
class ScanAndCartActivity : AppCompatActivity() {
    // UI组件 - 扫描部分
    private lateinit var scannerView: CodeScannerView
    private lateinit var btnBack: Button
    private lateinit var btnManualInputId: Button
    private lateinit var productInfoContainer: View
    private lateinit var tvProductId: TextView
    private lateinit var tvProductName: TextView
    private lateinit var tvProductPrice: TextView
    private lateinit var tvProductBarcode: TextView
    private lateinit var btnAddToCart: Button
    private lateinit var btnBackToScan: Button

    // UI组件 - 购物车部分
    private lateinit var recyclerViewCartItems: RecyclerView
    private lateinit var tvEmptyCartMessage: TextView
    private lateinit var progressBar: View
    private lateinit var btnClearCart: Button
    private lateinit var btnCheckout: Button
    private lateinit var checkoutSummaryContainer: View
    private lateinit var tvTotalQuantity: TextView
    private lateinit var tvTotalAmount: TextView

    // 主服务实例
    private lateinit var mainService: MainService
    // 条形码扫描器
    private lateinit var codeScanner: CodeScanner
    // 购物车商品列表
    private lateinit var cartItems: MutableList<CartItem>
    // 购物车商品适配器
    private lateinit var cartAdapter: CartAdapter
    // 线程池，用于执行后台任务
    private val executorService = java.util.concurrent.Executors.newSingleThreadExecutor()

    companion object {
        // 日志标签
        private const val TAG = "ScanAndCartActivity"
        // 结算结果请求码
        private const val CHECKOUT_RESULT_REQUEST = 106
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_scan_and_cart)

        // 初始化UI组件 - 扫描部分
        scannerView = findViewById(R.id.scannerView)
        btnBack = findViewById(R.id.btn_back)
        btnManualInputId = findViewById(R.id.btn_manual_input_id)
        productInfoContainer = findViewById(R.id.product_info_container)
        tvProductId = findViewById(R.id.tv_product_id)
        tvProductName = findViewById(R.id.tv_product_name)
        tvProductPrice = findViewById(R.id.tv_product_price)
        tvProductBarcode = findViewById(R.id.tv_product_barcode)
        btnAddToCart = findViewById(R.id.btn_add_to_cart)
        btnBackToScan = findViewById(R.id.btn_back_to_scan)

        // 初始化UI组件 - 购物车部分
        recyclerViewCartItems = findViewById(R.id.recycler_view_cart_items)
        tvEmptyCartMessage = findViewById(R.id.tv_empty_cart_message)
        progressBar = findViewById(R.id.progress_bar)
        btnClearCart = findViewById(R.id.btn_clear_cart)
        btnCheckout = findViewById(R.id.btn_checkout)
        checkoutSummaryContainer = findViewById(R.id.checkout_summary_container)
        tvTotalQuantity = findViewById(R.id.tv_total_quantity)
        tvTotalAmount = findViewById(R.id.tv_total_amount)

        // 初始化主服务
        mainService = MainService(this)

        // 初始化条形码扫描器
        setupCodeScanner()

        // 设置按钮点击监听器
        setupButtonListeners()

        // 初始化购物车RecyclerView
        setupRecyclerView()

        // 加载购物车数据
        loadCartItems()

        // 检查相机权限
        checkCameraPermission()
    }

    /**
     * 初始化条形码扫描器
     */
    private fun setupCodeScanner() {
        codeScanner = CodeScanner(this, scannerView)

        // 配置扫描器参数
        codeScanner.apply {
            camera = CodeScanner.CAMERA_BACK
            formats = CodeScanner.ALL_FORMATS // 支持所有条码格式
            autoFocusMode = AutoFocusMode.SAFE
            scanMode = ScanMode.SINGLE
            isAutoFocusEnabled = true
            isFlashEnabled = false
        }

        // 设置解码回调
        codeScanner.decodeCallback = DecodeCallback {
            runOnUiThread {
                // 隐藏扫描器，显示商品信息
                scannerView.visibility = View.GONE
                productInfoContainer.visibility = View.VISIBLE

                // 查找对应商品
                findProductByBarcode(it.text)
            }
        }

        // 设置错误回调
        codeScanner.errorCallback = object : ErrorCallback {
            override fun onError(error: Throwable) {
                runOnUiThread {
                    Toast.makeText(this@ScanAndCartActivity, "相机初始化错误: ${error.message}", Toast.LENGTH_LONG).show()
                }
            }
        }

        // 设置扫描器点击事件（重新启动扫描）
        scannerView.setOnClickListener {
            codeScanner.startPreview()
        }
    }

    /**
     * 设置按钮点击监听器
     */
    private fun setupButtonListeners() {
        // 返回按钮点击事件
        btnBack.setOnClickListener {
            finish()
        }

        // 手动输入商品ID按钮点击事件
        btnManualInputId.setOnClickListener {
            showManualIdInputDialog()
        }

        // 添加到购物车按钮点击事件 - 将在显示商品信息时设置

        // 返回扫描按钮点击事件
        btnBackToScan.setOnClickListener {
            productInfoContainer.visibility = View.GONE
            scannerView.visibility = View.VISIBLE
            codeScanner.startPreview()
        }

        // 清空购物车按钮点击事件
        btnClearCart.setOnClickListener {
            clearShoppingCart()
        }

        // 结算按钮点击事件
        btnCheckout.setOnClickListener {
            checkout()
        }
    }

    /**
     * 初始化RecyclerView
     */
    private fun setupRecyclerView() {
        recyclerViewCartItems.layoutManager = LinearLayoutManager(this)
        cartItems = mutableListOf()
        cartAdapter = CartAdapter(cartItems, this::onQuantityChange, this::onRemoveItem)
        recyclerViewCartItems.adapter = cartAdapter
    }

    /**
     * 检查相机权限
     */
    private fun checkCameraPermission() {
        if (!mainService.hasPermission(Manifest.permission.CAMERA)) {
            mainService.requestPermission(Manifest.permission.CAMERA, MainService.PERMISSION_CAMERA_REQUEST_CODE)
        } else {
            startScanner()
        }
    }

    /**
     * 启动扫描器
     */
    private fun startScanner() {
        codeScanner.startPreview()
    }

    /**
     * 通过条形码查找商品
     */
    private fun findProductByBarcode(barcode: String) {
        // 使用线程池执行后台查询
        executorService.execute {
            val product = mainService.getProductByBarcode(barcode)
            runOnUiThread {
                if (product != null) {
                    showProductInfo(product)
                } else {
                    showProductNotFound(barcode)
                }
            }
        }
    }

    /**
     * 通过ID查找商品
     */
    private fun findProductById(productId: String) {
        // 使用线程池执行后台查询
        executorService.execute {
            val products = mainService.searchProducts(productId)
            runOnUiThread {
                when {
                    products.isEmpty() -> {
                        showProductNotFound(productId)
                    }
                    products.size == 1 -> {
                        showProductInfo(products[0])
                    }
                    else -> {
                        showProductSelectionDialog(products)
                    }
                }
            }
        }
    }

    /**
     * 显示商品选择对话框
     */
    private fun showProductSelectionDialog(products: List<Product>) {
        val productNames = products.map { "${it.getFormattedId()} - ${it.name} (¥${String.format("%.2f", it.price)})" }.toTypedArray()
        
        AlertDialog.Builder(this)
            .setTitle("选择商品")
            .setItems(productNames) { dialog, which ->
                val selectedProduct = products[which]
                showProductInfo(selectedProduct)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 显示商品信息
     */
    private fun showProductInfo(product: Product) {
        tvProductId.text = product.getFormattedId()
        tvProductName.text = product.name
        tvProductPrice.text = String.format("¥%.2f", product.price)
        tvProductBarcode.text = if (product.barcode.isEmpty()) "未设置" else product.barcode

        // 设置添加到购物车按钮点击事件
        btnAddToCart.visibility = View.VISIBLE
        btnAddToCart.setOnClickListener {
            addToCart(product)
        }
    }

    /**
     * 显示商品未找到提示
     */
    private fun showProductNotFound(identifier: String) {
        tvProductId.text = "--"
        tvProductName.text = "未找到商品"
        tvProductPrice.text = "¥0.00"
        tvProductBarcode.text = identifier

        // 隐藏添加到购物车按钮
        btnAddToCart.visibility = View.GONE
    }

    /**
     * 将商品添加到购物车
     */
    private fun addToCart(product: Product) {
        mainService.addToCart(product) { success ->
            runOnUiThread {
                if (success) {
                    // 添加商品后立即打印日志，便于调试
                    Log.d("ScanAndCartActivity", "商品添加到购物车成功: ${product.name}")
                    Toast.makeText(this@ScanAndCartActivity, "已添加到购物车", Toast.LENGTH_SHORT).show()
                    // 返回扫描界面
                    productInfoContainer.visibility = View.GONE
                    scannerView.visibility = View.VISIBLE
                    codeScanner.startPreview()
                    // 确保购物车列表被正确更新
                    loadCartItems()
                } else {
                    Log.d("ScanAndCartActivity", "商品添加到购物车失败: ${product.name}")
                    Toast.makeText(this@ScanAndCartActivity, "添加到购物车失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    /**
     * 显示手动输入商品ID对话框
     */
    private fun showManualIdInputDialog() {
        val builder = AlertDialog.Builder(this)
        val inflater = layoutInflater
        val dialogView = inflater.inflate(R.layout.dialog_input_product_id, null)
        val etProductId = dialogView.findViewById<com.google.android.material.textfield.TextInputEditText>(R.id.et_product_id)

        builder.setView(dialogView)
            .setTitle("输入商品ID或名称")
            .setPositiveButton("确定") {
                dialog, which ->
                val query = etProductId.text.toString().trim()
                if (query.isNotEmpty()) {
                    // 隐藏扫描器，显示商品信息
                    scannerView.visibility = View.GONE
                    productInfoContainer.visibility = View.VISIBLE

                    // 查找对应商品
                    findProductById(productId = query)
                } else {
                    Toast.makeText(this@ScanAndCartActivity, "请输入商品ID或名称", Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 加载购物车数据
     */
    private fun loadCartItems() {
        // 显示加载指示器
        progressBar.visibility = View.VISIBLE
        recyclerViewCartItems.visibility = View.GONE
        tvEmptyCartMessage.visibility = View.GONE
        checkoutSummaryContainer.visibility = View.GONE

        // 添加日志，记录加载购物车数据的时间点
        Log.d("ScanAndCartActivity", "开始加载购物车数据")
        
        mainService.getShoppingCartItems {
            items ->
            runOnUiThread {
                // 添加日志，记录获取到的购物车数据
                Log.d("ScanAndCartActivity", "获取到购物车数据: items=${items?.size ?: 0}")
                
                // 隐藏加载指示器
                progressBar.visibility = View.GONE

                cartItems.clear()
                if (items != null && items.isNotEmpty()) {
                    cartItems.addAll(items)
                    // 添加日志，记录添加到适配器的商品数量
                    Log.d("ScanAndCartActivity", "购物车商品数量: ${cartItems.size}")
                    
                    recyclerViewCartItems.visibility = View.VISIBLE
                    btnClearCart.visibility = View.VISIBLE
                    btnCheckout.visibility = View.VISIBLE
                    checkoutSummaryContainer.visibility = View.VISIBLE
                    cartAdapter.notifyDataSetChanged()
                    updateCheckoutSummary()
                } else {
                    // 添加日志，记录购物车为空
                    Log.d("ScanAndCartActivity", "购物车为空")
                    
                    tvEmptyCartMessage.visibility = View.VISIBLE
                    recyclerViewCartItems.visibility = View.GONE
                    btnClearCart.visibility = View.GONE
                    btnCheckout.visibility = View.GONE
                    checkoutSummaryContainer.visibility = View.GONE
                }
            }
        }
    }

    /**
     * 更新结算摘要信息
     */
    private fun updateCheckoutSummary() {
        val totalQuantity = cartItems.sumOf { it.quantity }
        val totalAmount = cartItems.sumOf { it.getSubtotal() }

        tvTotalQuantity.text = String.format("%d", totalQuantity)
        tvTotalAmount.text = String.format("¥%.2f", totalAmount)
    }

    /**
     * 数量变化事件处理
     */
    private fun onQuantityChange(position: Int, newQuantity: Int) {
        if (newQuantity > 0) {
            // 更新商品数量
            val cartItem = cartItems[position]
            mainService.updateCartItemQuantity(cartItem.product.id, newQuantity) {
                success ->
                runOnUiThread {
                    if (success) {
                        cartItem.quantity = newQuantity
                        cartAdapter.notifyItemChanged(position)
                        updateCheckoutSummary()
                    } else {
                        Toast.makeText(this, "更新数量失败", Toast.LENGTH_SHORT).show()
                        cartAdapter.notifyItemChanged(position) // 恢复原有数量显示
                    }
                }
            }
        } else {
            // 数量为0，移除商品
            onRemoveItem(position)
        }
    }

    /**
     * 移除商品事件处理
     */
    private fun onRemoveItem(position: Int) {
        val cartItem = cartItems[position]
        mainService.removeFromCart(cartItem.product.id) {
            success ->
            runOnUiThread {
                if (success) {
                    cartItems.removeAt(position)
                    cartAdapter.notifyItemRemoved(position)
                    updateCheckoutSummary()

                    // 如果购物车为空，更新界面显示
                    if (cartItems.isEmpty()) {
                        tvEmptyCartMessage.visibility = View.VISIBLE
                        recyclerViewCartItems.visibility = View.GONE
                        btnClearCart.visibility = View.GONE
                        btnCheckout.visibility = View.GONE
                        checkoutSummaryContainer.visibility = View.GONE
                    }
                } else {
                    Toast.makeText(this, "移除商品失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    /**
     * 清空购物车
     */
    private fun clearShoppingCart() {
        if (cartItems.isEmpty()) return

        // 显示确认对话框
        AlertDialog.Builder(this)
            .setTitle("清空购物车")
            .setMessage("确定要清空购物车吗？")
            .setPositiveButton("确定") {
                _, _ ->
                mainService.clearShoppingCart() {
                    success ->
                    runOnUiThread {
                        if (success) {
                            cartItems.clear()
                            cartAdapter.notifyDataSetChanged()
                            tvEmptyCartMessage.visibility = View.VISIBLE
                            recyclerViewCartItems.visibility = View.GONE
                            btnClearCart.visibility = View.GONE
                            btnCheckout.visibility = View.GONE
                            checkoutSummaryContainer.visibility = View.GONE
                            Toast.makeText(this, "购物车已清空", Toast.LENGTH_SHORT).show()
                        } else {
                            Toast.makeText(this, "清空购物车失败", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 结算购物车
     */
    private fun checkout() {
        if (cartItems.isEmpty()) return

        // 计算总金额
        val totalAmount = cartItems.sumOf { it.getSubtotal() }

        // 显示结算确认对话框
        AlertDialog.Builder(this)
            .setTitle("确认结算")
            .setMessage("共 ${cartItems.size} 件商品，合计: ¥${String.format("%.2f", totalAmount)}")
            .setPositiveButton("确认") {
                _, _ ->
                // 生成收据
                generateReceipt()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 生成收据
     */
    private fun generateReceipt() {
        // 生成收据号
        val receiptNumber = generateReceiptNumber()
        // 获取当前时间
        val receiptTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())
        // 计算总金额
        val totalAmount = cartItems.sumOf { it.getSubtotal() }

        // 跳转到收据显示页面
        val intent = Intent(this, ReceiptActivity::class.java)
        intent.putExtra("receiptNumber", receiptNumber)
        intent.putExtra("receiptTime", receiptTime)
        intent.putExtra("totalAmount", totalAmount)
        intent.putExtra("cartItems", ArrayList(cartItems))
        startActivityForResult(intent, CHECKOUT_RESULT_REQUEST)
    }

    /**
     * 生成收据号
     */
    private fun generateReceiptNumber(): String {
        val dateFormat = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())
        return "R-${dateFormat.format(Date())}"
    }

    /**
     * 处理权限请求结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == MainService.PERMISSION_CAMERA_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == android.content.pm.PackageManager.PERMISSION_GRANTED) {
                startScanner()
            } else {
                Toast.makeText(this, "需要相机权限才能扫描条形码", Toast.LENGTH_SHORT).show()
                finish()
            }
        }
    }

    /**
     * 处理结算结果
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == CHECKOUT_RESULT_REQUEST && resultCode == RESULT_OK) {
            // 结算完成，清空购物车
            mainService.clearShoppingCart() {
                success ->
                runOnUiThread {
                    if (success) {
                        loadCartItems() // 重新加载购物车数据
                    }
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if (this::codeScanner.isInitialized) {
            codeScanner.startPreview()
        }
        // 每次恢复时更新购物车数据
        loadCartItems()
    }

    override fun onPause() {
        if (this::codeScanner.isInitialized) {
            codeScanner.releaseResources()
        }
        super.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        // 清理线程池资源
        executorService.shutdown()
    }

    /**
     * 购物车商品适配器类
     */
    inner class CartAdapter(
        private val cartItems: MutableList<CartItem>,
        private val onQuantityChange: (Int, Int) -> Unit,
        private val onRemoveItem: (Int) -> Unit
    ) : androidx.recyclerview.widget.RecyclerView.Adapter<CartAdapter.CartItemViewHolder>() {

        inner class CartItemViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {
            // 使用findViewById替代数据绑定来避免可能的绑定问题
            val tvProductName: TextView = itemView.findViewById(R.id.tv_product_name)
            val tvProductPrice: TextView = itemView.findViewById(R.id.tv_product_price)
            val tvQuantity: TextView = itemView.findViewById(R.id.tv_quantity)
            val tvSubtotal: TextView = itemView.findViewById(R.id.tv_subtotal)
            val btnDecreaseQuantity: ImageButton = itemView.findViewById(R.id.btn_decrease_quantity)
            val btnIncreaseQuantity: ImageButton = itemView.findViewById(R.id.btn_increase_quantity)
            val btnRemoveItem: ImageButton = itemView.findViewById(R.id.btn_remove_item)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartItemViewHolder {
            try {
                val view = layoutInflater.inflate(R.layout.item_cart, parent, false)
                return CartItemViewHolder(view)
            } catch (e: Exception) {
                Log.e(TAG, "创建ViewHolder失败", e)
                // 返回一个空的ViewHolder以避免应用崩溃
                return CartItemViewHolder(FrameLayout(parent.context))
            }
        }

        override fun onBindViewHolder(holder: CartItemViewHolder, position: Int) {
            try {
                if (position < 0 || position >= cartItems.size) {
                    Log.w(TAG, "无效的位置: $position")
                    return
                }
                
                val cartItem = cartItems[position]
                val product = cartItem.product

                // 显示商品信息
                holder.tvProductName.text = product.name
                holder.tvProductPrice.text = String.format("¥%.2f", product.price)
                holder.tvQuantity.text = cartItem.quantity.toString()
                holder.tvSubtotal.text = String.format("¥%.2f", cartItem.getSubtotal())

                // 设置减少数量按钮点击事件
                holder.btnDecreaseQuantity.setOnClickListener {
                    val newQuantity = cartItem.quantity - 1
                    onQuantityChange(position, newQuantity)
                }

                // 设置增加数量按钮点击事件
                holder.btnIncreaseQuantity.setOnClickListener {
                    val newQuantity = cartItem.quantity + 1
                    onQuantityChange(position, newQuantity)
                }

                // 设置删除按钮点击事件
                holder.btnRemoveItem.setOnClickListener {
                    onRemoveItem(position)
                }
            } catch (e: Exception) {
                Log.e(TAG, "绑定ViewHolder数据失败", e)
            }
        }

        override fun getItemCount(): Int {
            return cartItems.size
        }
    }
}